package com.kexilo.core.common.interceptor;

import com.kexilo.core.common.config.ApiVersionConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * API版本控制拦截器
 * 
 * @author Kexilo
 */
@Component
public class ApiVersionInterceptor implements HandlerInterceptor {
    
    private static final Logger log = LoggerFactory.getLogger(ApiVersionInterceptor.class);

    @Autowired
    private ApiVersionConfig apiVersionConfig;

    private static final Pattern VERSION_PATTERN = Pattern.compile("^/api/(v\\d+)/.*");
    private static final String API_VERSION_HEADER = "API-Version";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!apiVersionConfig.isEnabled()) {
            return true;
        }

        String requestPath = request.getRequestURI();
        String version = extractVersionFromPath(requestPath);
        
        // 如果URL中没有版本信息，尝试从Header获取
        if (version == null) {
            version = request.getHeader(API_VERSION_HEADER);
        }
        
        // 如果都没有，使用默认版本
        if (version == null) {
            version = apiVersionConfig.getDefaultVersion();
            log.debug("使用默认版本: {}", version);
        }

        // 验证版本有效性
        if (!apiVersionConfig.isValidVersion(version)) {
            log.warn("无效的API版本: {}, 请求路径: {}", version, requestPath);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }

        // 检查版本状态并添加相应的响应头
        ApiVersionConfig.VersionInfo versionInfo = apiVersionConfig.getVersionInfo(version);
        if (versionInfo != null) {
            // 设置版本信息到响应头
            response.setHeader("API-Version", version);
            response.setHeader("API-Version-Status", versionInfo.getStatus());

            // 如果版本已弃用，添加弃用相关的响应头
            if ("deprecated".equals(versionInfo.getStatus())) {
                if (versionInfo.getDeprecationNotice() != null) {
                    response.setHeader("Deprecation", versionInfo.getDeprecationNotice());
                }
                if (versionInfo.getSunsetAt() != null) {
                    response.setHeader("Sunset", versionInfo.getSunsetAt().format(DATE_FORMATTER));
                }
                if (versionInfo.getMigrationGuide() != null) {
                    response.setHeader("Link", String.format("<%s>; rel=\"migrate\"", versionInfo.getMigrationGuide()));
                }
                log.warn("使用已弃用的API版本: {}, 请求路径: {}", version, requestPath);
            }
        }

        // 将版本信息存储到请求属性中，供后续处理使用
        request.setAttribute("apiVersion", version);
        request.setAttribute("apiVersionInfo", versionInfo);

        return true;
    }

    /**
     * 从请求路径中提取版本信息
     */
    private String extractVersionFromPath(String path) {
        Matcher matcher = VERSION_PATTERN.matcher(path);
        if (matcher.matches()) {
            return matcher.group(1);
        }
        return null;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 记录API访问日志
        String version = (String) request.getAttribute("apiVersion");
        if (version != null) {
            log.debug("API调用完成 - 版本: {}, 路径: {}, 状态: {}", 
                version, request.getRequestURI(), response.getStatus());
        }
    }
}

